const Koa = require('koa');
const cors = require('@koa/cors')
const path = require('path')
const staticFiles = require('koa-static')
const bodyParser = require('koa-bodyparser')

const app = new Koa();

const JSON_MIME = 'application/json'
const {open} = require('./lib/db/connect')
const router = require('./routes')
const logger = require('./middlewares/log')

open()

app.use(logger)
app.use(cors({
  origin: '*'
}))
 
app.use(bodyParser({multipart: true}))

app.use(staticFiles(path.resolve(__dirname,'./uploads'),{
  maxage: 30 * 24 * 60 * 60 * 100
}))

app.use(async (Context,next) => {
  try{
    await next()
  } catch (ex) {
    context.logger.error(ex.stack || ex)
    context.body = {
      status: -1,
      message: ex.message || ex,
      code: ex.status
    }
  }
});

app.use(router.routes())
app.use(router.allowMethods())
 
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});


